/*
 * @Descripttion: 
 * @version: 
 * @Author: wangzhilei
 * @Date: 2021-09-20 02:37:29
 * @LastEditors: wangzhilei
 * @LastEditTime: 2021-09-20 07:06:11
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

const int SERV_PORT = 6000;

const int MAXLINE = 2048;

void dg_cli(FILE *fp, int sockfd, const struct sockaddr *pservaddr, socklen_t servlen)
{
    int n;
    char sendline[MAXLINE], recvline[MAXLINE + 1];
    while (fgets(sendline, MAXLINE, fp) != NULL)
    {
        if (sendto(sockfd, sendline, strlen(sendline), 0, pservaddr, servlen) < 0)
        {
            perror("sendto error");
            exit(1);
        }
        if ((n = recvfrom(sockfd, recvline, MAXLINE, 0, NULL, NULL)) < 0)
        {
            perror("recvfrom error");
            exit(1);
        }
        recvline[n] = '\0';
        fputs(recvline, stdout);
    }
}
int main(int argc, char **argv)
{
    int sockfd;
    struct sockaddr_in servaddr;

    if (argc != 2)
    {
        perror("usage:tcpcli");
        exit(1);
    }

    //1.创建套接字
    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
    {
        perror("socket error");
        exit(1);
    }
    //2.设置链接服务器地址结体
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(SERV_PORT);
    if ((inet_pton(AF_INET, argv[1], &servaddr.sin_addr)) <= 0)
    {
        printf("inet_pton error for %s\n", argv[1]);
        exit(1);
    }
    if ((sockfd == socket(AF_INET, SOCK_DGRAM, 0)) < 0)
    {
        perror("socket error");
    }
    dg_cli(stdin, sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
    exit(0);
}